import java.util.*;

public class test {
    // 6
    //[[0,1],[0,2],[0,3],[3,4],[4,5]]
    public static void main(String[] args) {
        System.out.println(findMinHeightTrees(6, new int[][]{{0, 1}, {0, 2}, {0, 3}, {3, 4}, {4, 5}}));
    }
    public static List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> ans = new ArrayList<>();
        if(n == 1){
            ans.add(0);
            return ans;
        }
        List<Integer>[] path = new ArrayList[n];
        int[] in = new int[n];
        Arrays.fill(path, new ArrayList<>());
        for(int[] e : edges){
            int x = e[0]; int y = e[1];
            path[x].add(y);
            path[y].add(x);
            in[x]++;
            in[y]++;
        }
        Deque<Integer> queue = new ArrayDeque<>();
        for(int i = 0; i < n; i++){
            if(in[i] == 1){
                queue.offer(i);
            }
        }

        while(!queue.isEmpty()){
            ans.clear();
            for(int i = queue.size() - 1; i >= 0; i--){
                int ret = queue.poll();
                ans.add(ret);
                for(int y : path[ret]){
                    if(--in[y] == 1){
                        queue.offer(y);
                    }
                }
            }
        }
        return ans;
    }

}
